package com.bwie.auth.service.imp;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.UserFeignService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserRequest;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
public class AuthServiceImp implements AuthService {
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Override
    public Result sendCode(String phone) {
        //验证手机号格式是否正确
        if(!validatePhone(phone)){
            return Result.error("手机号格式不正确!");
        }
        //验证手机号是否是系统用户
        Result<User> phone1 = userFeignService.findByUserPhone(phone);
        User user = phone1.getData();
        if(null==user){
            return Result.error("手机号不是系统用户");
        }
        //获取验证码
        String code = RandomUtil.randomNumbers(4);
        //存储用户信息
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return Result.success(code);
    }

    @Override
    public Result<UserResponse> login(UserRequest userRequest) {
        //验证参数
        if(StringUtils.isAllBlank(userRequest.getPhone(),userRequest.getCode())){
            return Result.error("验证手机号或验证码不能为空");
        }
        //验证手机号是否存在
        if(StringUtils.isEmpty(userRequest.getPhone())){
            return Result.error("手机号不存在");
        }
        Result<User> phone = userFeignService.findByUserPhone(userRequest.getPhone());
        User user = phone.getData();
        if(null==user){
            return Result.error("验证码已过期");
        }
        //登录成功 生成token
        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        //存储用户信息
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(user),10,TimeUnit.MINUTES);
        //返回响应数据
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(token);
        userResponse.setTimes("10Min");
        return Result.success(userResponse);
    }

    @Override
    public User userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userJson,User.class);
    }

    private boolean validatePhone(String phone) {
        //正则表达式
        Pattern compile = Pattern.compile("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[189]))\\d{8}$");
        return compile.matcher(phone).matches();
    }
}
